const express = require('express')
const bitcoin = require('bitcoinjs-lib')

const app = express()

app.post('/', (req, res) => {
  if (!req.query) return res.sendStatus(400)

  let address = req.query.address

  let decodedAddress = bitcoin.address.fromBase58Check(address)
  let version = decodedAddress['version']
  console.log("versions==="+version)

let resjson={}

try {

            switch (version) {
      					case 5:
      						message = "Mainnet p2sh address: ";
      						version = 50;
      						break;
      					case 50:
      						message = "Mainnet p2sh address (deprecated): ";
      						version = 5;
      						break;
      					case 196:
      						message = "Testnet p2sh address: ";
      						version = 58;
      						break;
      					case 58:
      						message = "Testnet p2sh address (deprecated): ";
      						version = 196;
      						break;
      					default:
      						throw "unknown";
                                     }


					  let newAddress = bitcoin.address.toBase58Check(decodedAddress['hash'], version)
					   resjson={
								  "newAddress":newAddress,
								  "message":message
								  }
					  res.send(resjson)



                 }catch(err) {
      				message = "Please enter a valid address."
      			    
					 resjson={
								  "newAddress":"",
							       "message":"Please enter a valid address."

								  }

					res.send(resjson)
      			}


})

app.listen(3002, () => {
  console.log('listening on port: 3002')
})
